package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.cache.redis.RedisKeyBuilder;
import com.gitee.apanlh.util.cache.redis.api.RedisString;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.ClassConvertUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyHuaRon;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeHuaRon;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 安心分期（出）&华融 全28
 * 全流程https://www.showdoc.com.cn/2598834033690034  密码：123456
 *
 * @author WJB
 */
@ApiPlan(productId = "370", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatHuaRonPhoneMd5Convert implements ApiPlatformPhoneMd5ConvertHandler {

    private static final String CHANNEL_CODE = "9SAXYADR";
    private static final String KEY = "82d5579a9e19a0705d8e8f8ca52aab3a";
    public static final RedisString PLAN_MATCH_HUA_RONG = RedisKeyBuilder.builder().withKeys("temp_hua_rong").buildString();

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) {
        ApiPlatDataExchangeHuaRon data = new ApiPlatDataExchangeHuaRon();
        data.setPhone_md5(apiDataExchangeParameter.getPhoneMd5());
        //  年龄
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getAge())) {
            data.setAge(ClassConvertUtils.toInt(apiDataExchangeParameter.getAge()));
        }
        //  性别
        Integer sex = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "1", 2)
                .when(apiDataExchangeParameter.getSex(), "0", 1)
                .end(1);
        data.setGender(sex);
        //  城市编码
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getAreaCode())) {
            data.setCity_code(Integer.valueOf(apiDataExchangeParameter.getAreaCode()));
        }
        //  贷款额度
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 30000)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 50000)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 100000)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 200000)
                .end();
        data.setMoney(money);
        //  芝麻分
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 600)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 649)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 699)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 700)
                .end(600);
        data.setSesame(zhima);
        //  房产
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 2)
                .end(1);
        data.setRoom(house);
        //  车产
        Integer vehicle = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 2)
                .end(1);
        data.setCar(vehicle);
        //  公积金
        Integer providentFund = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 2)
                .end(1);
        data.setGjj(providentFund);
        //  社保
        Integer socialSecurity = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 2)
                .end(1);
        data.setSocial(socialSecurity);
        //  商业保险
        Integer commericalInsurance = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 2)
                .end(1);
        data.setPolicy(commericalInsurance);
        //  营业执照
        Integer bizLicenseYear = ChooseEq.create()
                .when(apiDataExchangeParameter.getBizLicenseYear(), "1", 1)
                .when(apiDataExchangeParameter.getBizLicenseYear(), "2", 2)
                .when(apiDataExchangeParameter.getBizLicenseYear(), "3", 2)
                .when(apiDataExchangeParameter.getBizLicenseYear(), "4", 2)
                .end(1);
        data.setBusiness(bizLicenseYear);
        //  信用卡
        Integer creditCard = ChooseEq.create()
                .when(apiDataExchangeParameter.getCreditLimit(), "1", 1)
                .when(apiDataExchangeParameter.getCreditLimit(), "2", 2)
                .when(apiDataExchangeParameter.getCreditLimit(), "3", 2)
                .when(apiDataExchangeParameter.getCreditLimit(), "4", 2)
                .when(apiDataExchangeParameter.getCreditLimit(), "5", 2)
                .when(apiDataExchangeParameter.getCreditLimit(), "6", 2)
                .end(1);
        data.setCredit_card(creditCard);
        //  花呗
        Integer huaBei = ChooseEq.create()
                .when(apiDataExchangeParameter.getHbLimit(), "1", 1)
                .when(apiDataExchangeParameter.getHbLimit(), "2", 2)
                .when(apiDataExchangeParameter.getHbLimit(), "3", 2)
                .when(apiDataExchangeParameter.getHbLimit(), "4", 2)
                .when(apiDataExchangeParameter.getHbLimit(), "5", 2)
                .end(1);
        data.setHuabei(huaBei);
        //  白条
        Integer btLimit = ChooseEq.create()
                .when(apiDataExchangeParameter.getBtLimit(), "1", 1)
                .when(apiDataExchangeParameter.getBtLimit(), "2", 2)
                .when(apiDataExchangeParameter.getBtLimit(), "3", 2)
                .when(apiDataExchangeParameter.getBtLimit(), "4", 2)
                .when(apiDataExchangeParameter.getBtLimit(), "5", 2)
                .end(1);
        data.setBaitiao(btLimit);
        // 信用记录
        Integer creditHistory = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", 1)
                .when(apiDataExchangeParameter.getOverdue(), "2", 2)
                .when(apiDataExchangeParameter.getOverdue(), "3", 2)
                .end(1);
        data.setCredit_record(creditHistory);
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        //  签名
        String signStr = "channel=" + CHANNEL_CODE + "&time=" + time + "&key=" + KEY;
        //  资质加密
        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));
        Map<String, Object> map = new HashMap<>();
        map.put("channel", CHANNEL_CODE);
        map.put("time", time);
        map.put("sign", MD5.create().digestToHex(signStr));
        map.put("encryptData", dataStr);
        return JsonUtils.toJson(map);
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) {
        ApiPlatApplyHuaRon data = new ApiPlatApplyHuaRon();
        data.setPhone(apiApplyParameter.getPhone());
        data.setName(apiApplyParameter.getUserName());
        //  年龄
        if (ValidParam.isNotEmpty(apiApplyParameter.getAge())) {
            data.setAge(ClassConvertUtils.toInt(apiApplyParameter.getAge()));
        }
        //  性别
        Integer sex = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "1", 2)
                .when(apiApplyParameter.getSex(), "0", 1)
                .end(1);
        data.setGender(sex);
        //  城市编码
        if (ValidParam.isNotEmpty(apiApplyParameter.getAreaCode())) {
            data.setCity_code(Integer.valueOf(apiApplyParameter.getAreaCode()));
        }
        //  贷款额度
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 30000)
                .when(apiApplyParameter.getLoanAmount(), "2", 50000)
                .when(apiApplyParameter.getLoanAmount(), "3", 100000)
                .when(apiApplyParameter.getLoanAmount(), "4", 200000)
                .end();
        data.setMoney(money);
        //  芝麻分
        Integer zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 600)
                .when(apiApplyParameter.getSesameCredit(), "2", 649)
                .when(apiApplyParameter.getSesameCredit(), "3", 699)
                .when(apiApplyParameter.getSesameCredit(), "4", 700)
                .end(600);
        data.setSesame(zhima);
        //  房产
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 2)
                .end(1);
        data.setRoom(house);
        //  车产
        Integer vehicle = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 1)
                .when(apiApplyParameter.getCarInfo(), "2", 2)
                .when(apiApplyParameter.getCarInfo(), "3", 2)
                .when(apiApplyParameter.getCarInfo(), "4", 2)
                .end(1);
        data.setCar(vehicle);
        //  公积金
        Integer providentFund = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 1)
                .when(apiApplyParameter.getProvidentFund(), "2", 2)
                .when(apiApplyParameter.getProvidentFund(), "3", 2)
                .when(apiApplyParameter.getProvidentFund(), "4", 2)
                .end(1);
        data.setGjj(providentFund);
        //  社保
        Integer socialSecurity = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 1)
                .when(apiApplyParameter.getSocialSecurity(), "2", 2)
                .when(apiApplyParameter.getSocialSecurity(), "3", 2)
                .when(apiApplyParameter.getSocialSecurity(), "4", 2)
                .end(1);
        data.setSocial(socialSecurity);
        //  商业保险
        Integer commericalInsurance = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 2)
                .end(1);
        data.setPolicy(commericalInsurance);
        //  营业执照
        Integer bizLicenseYear = ChooseEq.create()
                .when(apiApplyParameter.getBizLicenseYear(), "1", 1)
                .when(apiApplyParameter.getBizLicenseYear(), "2", 2)
                .when(apiApplyParameter.getBizLicenseYear(), "3", 2)
                .when(apiApplyParameter.getBizLicenseYear(), "4", 2)
                .end(1);
        data.setBusiness(bizLicenseYear);
        //  信用卡
        Integer creditCard = ChooseEq.create()
                .when(apiApplyParameter.getCreditLimit(), "1", 1)
                .when(apiApplyParameter.getCreditLimit(), "2", 2)
                .when(apiApplyParameter.getCreditLimit(), "3", 2)
                .when(apiApplyParameter.getCreditLimit(), "4", 2)
                .when(apiApplyParameter.getCreditLimit(), "5", 2)
                .when(apiApplyParameter.getCreditLimit(), "6", 2)
                .end(1);
        data.setCredit_card(creditCard);
        //  花呗
        Integer huaBei = ChooseEq.create()
                .when(apiApplyParameter.getHbLimit(), "1", 1)
                .when(apiApplyParameter.getHbLimit(), "2", 2)
                .when(apiApplyParameter.getHbLimit(), "3", 2)
                .when(apiApplyParameter.getHbLimit(), "4", 2)
                .when(apiApplyParameter.getHbLimit(), "5", 2)
                .end(1);
        data.setHuabei(huaBei);
        //  白条
        Integer btLimit = ChooseEq.create()
                .when(apiApplyParameter.getBtLimit(), "1", 1)
                .when(apiApplyParameter.getBtLimit(), "2", 2)
                .when(apiApplyParameter.getBtLimit(), "3", 2)
                .when(apiApplyParameter.getBtLimit(), "4", 2)
                .when(apiApplyParameter.getBtLimit(), "5", 2)
                .end(1);
        data.setBaitiao(btLimit);
        // 信用记录
        Integer creditHistory = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", 1)
                .when(apiApplyParameter.getOverdue(), "2", 2)
                .when(apiApplyParameter.getOverdue(), "3", 2)
                .end(1);
        data.setCredit_record(creditHistory);
        String productId = ApiPlatHuaRonPhoneMd5Convert.PLAN_MATCH_HUA_RONG.get(apiApplyParameter.dataExchangeApplyId(), String.class);
        // 创建协议对象
        ApiPlatApplyHuaRon.product product = new ApiPlatApplyHuaRon.product();
        product.setProduct_id(ClassConvertUtils.toInt(productId));
        product.setOrder_number(apiApplyParameter.dataExchangeApplyId());
        // 创建agreementList集合
        List<ApiPlatApplyHuaRon.agreementList> list = new ArrayList<>();
        // 创建agreementList对象
        ApiPlatApplyHuaRon.agreementList agreementList = new ApiPlatApplyHuaRon.agreementList();
        agreementList.setName("用户授权协议");
        agreementList.setUrl(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));
        // 添加协议
        list.add(agreementList);
        product.setAgreement_list(list);
        data.setProduct(product);

        String time = String.valueOf(System.currentTimeMillis() / 1000);
        //  签名
        String signStr = "channel=" + CHANNEL_CODE + "&time=" + time + "&key=" + KEY;
        //  资质加密
        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));
        Map<String, Object> map = new HashMap<>();
        map.put("channel", CHANNEL_CODE);
        map.put("time", time);
        map.put("sign", MD5.create().digestToHex(signStr));
        map.put("encryptData", dataStr);
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        JSONObject resData = jsonObject.getJSONObject("product");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        BigDecimal price = resData.getBigDecimal("price");
        String companyName = resData.getString("company_name");
        String productName = resData.getString("product_name");
        String logo = resData.getString("logo_url");
        String orderId = resData.getString("order_number");
        String callUrl = resData.getString("url");
        String productId = resData.getString("product_id");
        List<ApiProtocol> protocolList = new ArrayList<>();
        //  获取协议
        JSONArray listProtocolResult = resData.getJSONArray("agreement_list");
        IteratorUtils.array(listProtocolResult, (protocolResult, index) -> {
            JSONObject protocolObject = listProtocolResult.getJSONObject(index);
            ApiProtocol protocol = new ApiProtocol();
            protocol.setProtocolName(protocolObject.getString("name"));
            protocol.setProtocolUrl(protocolObject.getString("url"));
            protocolList.add(protocol);
        });

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();

        result.setPrice(price);
        result.setLogoPath(logo);
        result.setDisplayName(companyName);
        result.setProductName(productName);
        result.setApplyId(orderId);
        result.setCallUrl(callUrl);
        result.setProtocolList(protocolList);
        ApiPlatHuaRonPhoneMd5Convert.PLAN_MATCH_HUA_RONG.setForMinutes(orderId, productId, 10L);
        return result;
    }

}
